package com.one.shopping.ui.activity;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.one.shopping.AppContext;
import com.one.shopping.R;
import com.one.shopping.api.OneApi;
import com.one.shopping.entity.Orders;
import com.one.shopping.entity.Result;
import com.one.shopping.entity.ShoppingCart;
import com.one.shopping.ui.baseActivity.BaseActivity;
import com.one.shopping.util.GsonUtils;

import org.apache.http.Header;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author 谢惠锌
 * @date 创建时间：2016-1-6 下午10:50:56
 * @version 1.0
 */

public class OrderActivity extends BaseActivity {

	private TextView orderIdTv;
	private RadioGroup roleRgp;
	private RadioButton averageUserRbt;
	private RadioButton memberRbt;
	private EditText memberCardEt;
	private Button checkBtn;
	private TextView luckyOrderDataTv;
	private Button luckyOrderBtn;
	private TextView orderAmountDataTv;
	private TextView userDataTv;
	private Button confirmPaymentBtn;
	int flag;
	private String orderId;
	private int cardId;
	private TextView chectResultTv;
	private int role = 0;
	private int luckNum;
	private Random random = new Random();
	private double money;
	private ImageView checkIv;
	private int checkResult;
	private int userId;
	private int luckOdds = 5; // 幸运订单有几成几率可以中奖，当前5代表有5成几率可以中奖
	private boolean iscleck;
	private List<ShoppingCart> shoppingCarts;


	@Override
	protected int getContentViewId() {
		return R.layout.orders_activity;
	}

	@Override
	protected void initView() {
		super.initView();

		setTitle("支付订单");
		isVisibleReturn(true);
		returnBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});


		orderIdTv = (TextView) findViewById(R.id.orderIdDataTv);
		roleRgp = (RadioGroup) findViewById(R.id.roleRgp);
		averageUserRbt = (RadioButton) findViewById(R.id.averageUserRbt);
		memberRbt = (RadioButton) findViewById(R.id.memberRbt);
		memberCardEt = (EditText) findViewById(R.id.memberCardEt);
		chectResultTv = (TextView) findViewById(R.id.checkResultTv);
		checkBtn = (Button) findViewById(R.id.chectBtn);
		luckyOrderDataTv = (TextView) findViewById(R.id.luckyOrderDataTv);
		luckyOrderBtn = (Button) findViewById(R.id.luckyOrderBtn);
		orderAmountDataTv = (TextView) findViewById(R.id.orderAmountDataTv);
		userDataTv = (TextView) findViewById(R.id.userDataTv);
		confirmPaymentBtn = (Button) findViewById(R.id.confirmPaymentBtn);
		checkIv = (ImageView) findViewById(R.id.checkIV);

		// 接收前一个页面发送过来的值
		Intent intent = getIntent();
//		userId = getIntent().getIntExtra("userid", 1);
		userId = AppContext.getInstance().getLoginInfo().getId();
		money = getIntent().getDoubleExtra("total", 1);
		shoppingCarts = (List<ShoppingCart>) intent.getSerializableExtra("shoppingcartList");


		// 设置订单编号
		String orderId = String.valueOf(Calendar.getInstance().getTimeInMillis());
		orderIdTv.setText(orderId);

		// 设置订单总金额
		orderAmountDataTv.setText(money + "");

		// 订单总金额超过200则有机会抽幸运订单大奖
		if (money >= 200) {
			luckyOrderBtn.setVisibility(View.VISIBLE);
		} else {
			luckyOrderBtn.setVisibility(View.GONE);
			luckyOrderDataTv.setText("否");
		}

		// 设置收银员工号
		userDataTv.setText("" + userId);

		// 设置顾客身份监听
		roleRgp.setOnCheckedChangeListener(new OnCheckedChangeListenerImp());

		// 设置检测会员卡按钮监听
		iscleck = false;
		checkBtn.setOnClickListener(OnClickCheckBtnListener);

		// 设置幸运订单监听
		luckNum = 0;
		luckyOrderBtn.setOnClickListener(OnClickLuckyOrderBtnListener);

		// 设置确认支付监听
		confirmPaymentBtn.setOnClickListener(OnClickConfirmPaymentBtnListener);

	}

	/**
	 * 设置检测会员卡事件
	 */
	private OnClickListener OnClickCheckBtnListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			iscleck = true;
			if (role == 1 && memberCardEt.getText().toString().equals("")) {
				memberCardEt.setError("输入框不能为空");
			} else if (role == 0) {

			} else {
				int cardId = Integer.parseInt(memberCardEt.getText().toString());
				OneApi.queryCardId(cardId, new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,byte[] responseBody) {
						Result result = GsonUtils.fromJson(new String(responseBody), Result.class);
						if (result.getCode() == 200) {
							checkResult = 1;
							checkIv.setImageResource(R.mipmap.t);
							checkIv.setVisibility(View.VISIBLE);
						} else {
							checkResult = 0;
							checkIv.setImageResource(R.mipmap.f);
							checkIv.setVisibility(View.VISIBLE);
						}

					}

					@Override
					public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
						Toast.makeText(OrderActivity.this, "网络错误",Toast.LENGTH_SHORT).show();
					}
				});
			}

		}

	};

	/**
	 * 设置幸运订单事件
	 */
	private OnClickListener OnClickLuckyOrderBtnListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			int x = random.nextInt(10);
			if (x < luckOdds) {
				luckNum = 1;
				luckyOrderDataTv.setText("恭喜你中奖了！！你的订单将享受八折优惠！");
			} else {
				luckNum = 0;
				luckyOrderDataTv.setText("好可惜，差点成为幸运订单！");
			}
			luckyOrderBtn.setVisibility(View.GONE);
			findViewById(R.id.LuckyOrderTv).setVisibility(View.GONE);
		}

	};

	/**
	 * 确认付款事件
	 */
	private OnClickListener OnClickConfirmPaymentBtnListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			confirmPay();
		}

	};

	/**
	 * 确认付款
	 */
	private void confirmPay() {
		orderId = orderIdTv.getText().toString().trim();
		String cardNum = memberCardEt.getText().toString().trim();
		if (!cardNum.equals("")) {
			cardId = Integer.parseInt(cardNum);
		} else {
			cardId = 0;
		}

		if (role == 1 && memberCardEt.getText().toString().equals("")) {
			memberCardEt.setError("输入框不能为空");
		} else if (role == 1 && checkResult != 1) {
			memberCardEt.setError("会员卡号检测错误");
		} else if (role == 1 && !iscleck) {
			memberCardEt.setError("请检测会员卡号");
		} else {
			Orders order = new Orders();
			order.setId(orderId);
			order.setTotal(money);
			order.setCardId(cardId);
			order.setGoodLuck(luckNum);
			order.setUserId(userId);
			order.setDate(getDate());

			OneApi.addOrders(order, new AsyncHttpResponseHandler() {

				@Override
				public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
					Result result = GsonUtils.fromJson(new String(responseBody), Result.class);
					if (result.getCode() == 200) {
						iscleck = false;
						// 传值到下一个页面
						Intent intent = new Intent();
						intent.putExtra("orderId", orderId);
						intent.putExtra("cardId", cardId);
						intent.putExtra("money", money);
						intent.putExtra("luckNum", luckNum);
						intent.putExtra("userId", userId);
						intent.putExtra("shoppingcartList", (Serializable) shoppingCarts);
						intent.setClass(OrderActivity.this, OrdersDetailActivity.class);
						startActivity(intent);
					}
				}

				@Override
				public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
					Toast.makeText(OrderActivity.this, "网络错误",Toast.LENGTH_SHORT).show();
				}
			});
		}
	}

	/**
	 * 顾客身份单选按钮监听事件
	 */
	private class OnCheckedChangeListenerImp implements OnCheckedChangeListener {

		public void onCheckedChanged(RadioGroup group, int checkedId) {
			role = 0;
			if (averageUserRbt.getId() == checkedId) {
				role = 0;
				memberCardEt.setText("");
				checkBtn.setFocusable(false);
				memberCardEt.setFocusable(false);
				memberCardEt.setFocusableInTouchMode(false);
			} else if (memberRbt.getId() == checkedId) {
				role = 1;
				checkBtn.setFocusable(true);
				memberCardEt.setFocusableInTouchMode(true);
				memberCardEt.setFocusable(true);
				memberCardEt.requestFocus();
			}

		}
	}

	/**
	 * 获取日期
	 *
	 * @return String
	 */
	private String getDate() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		String date = formatter.format(curDate);
		return date;
	}
}
